<?php
    /**
     * Created by PhpStorm.
     * User: zgh
     * Date: 2021-07-31
     * Time: 15:44
     */

    namespace app\api\middleware;


    use app\api\service\LoginService;
    use app\common\Annotation\ApiControllerAnnotation;
    use app\common\Annotation\ApiNodeAnotation;
    use app\common\Annotation\ControllerAnnotation;
    use app\common\Annotation\NodeAnotation;
    use app\common\service\AuthService;
    use Doctrine\Common\Annotations\AnnotationReader;
    use think\facade\Request;

    class LoginMiddleware
    {
        const TYPE_NO_LOGIN = 0;
        const TYPE_LOGON = 1;
        const LOGIN_CODE = -888;

        public function handle($request, \Closure $next)
        {
            $utk = $request->header('utk') ?: "";
            $customer_type = $request->header('customer-type') ?: "";
            $user_id = 0;
            $login_status = 0;//登陆状态
            if ($utk) {
                $user_id = LoginService::getUserIdByTokenFromCache($utk);
            }
            if($user_id){
                $login_status = 1;
            }
            $request->user_id = $user_id;
            $request->utk = $utk;
            $request->customer_type = $customer_type;
            $request->LOGIN_STATUS = $login_status;
            $current_controller_class = AuthService::getCurrentControllerClass();
            $auth_type = self::TYPE_NO_LOGIN; //默认是不需要登陆的
            $reflectionClass = new \ReflectionClass($current_controller_class);
            $reflectionMethod = $reflectionClass->getMethod(Request::action());
            try {
                $reader = new AnnotationReader();
                $class_annotation = $reader->getClassAnnotation($reflectionClass, ApiControllerAnnotation::class);
                $method_annotation = $reader->getMethodAnnotation($reflectionMethod, ApiNodeAnotation::class);
                if ($class_annotation !== null && isset($class_annotation->auth)) {
                    $auth_type = $class_annotation->auth;
                }
                if ($method_annotation !== null && isset($method_annotation->auth)) {
                    $auth_type = $method_annotation->auth;
                }
            } catch (\Exception $exception) {

            }
            if ($auth_type == self::TYPE_LOGON && empty($user_id)) {
                return json_response("请先登陆", [], [], self::LOGIN_CODE);
            }
            return $next($request);
        }
    }